import { computed, ref } from 'vue'
import { useCalculatorStore } from '@/stores/calculator'

// 计算器状态
export const display = ref('0') // 显示屏内容
export const currentInput = ref('') // 当前输入
export const operator = ref('') // 当前操作符
export const previousInput = ref('') // 上一个输入
export const waitingForNewInput = ref(false) // 是否等待新输入
export const hasCalculated = ref(false) // 是否已经计算过结果

// 新增状态
export const formula = ref('') // 公式显示
export const result = ref('') // 结果显示
export const showHistoryInDisplay = ref(false) // 在显示区域显示历史记录
export const fullFormula = ref('') // 完整公式记录（用于连续计算）
export const expressionParts = ref<string[]>([]) // 表达式部分数组
export const openBrackets = ref(0) // 未闭合的左括号数

// 历史记录
export const history = ref<Array<{
  id: string
  expression: string
  result: string
  timestamp: string
}>>([])

// 历史记录显示状态
export const showHistory = ref(false)

// 计算结果的最大长度
const MAX_DISPLAY_LENGTH = 12

// 按钮配置
export const buttonRows = [
  [
    { text: 'C', type: 'clear', class: 'clear' },
    { text: '( )', type: 'parentheses', class: 'function' },
    { text: '%', type: 'operator', class: 'function' },
    { text: '÷', type: 'operator', class: 'operator' },
  ],
  [
    { text: '7', type: 'number', class: 'number' },
    { text: '8', type: 'number', class: 'number' },
    { text: '9', type: 'number', class: 'number' },
    { text: '×', type: 'operator', class: 'operator' },
  ],
  [
    { text: '4', type: 'number', class: 'number' },
    { text: '5', type: 'number', class: 'number' },
    { text: '6', type: 'number', class: 'number' },
    { text: '-', type: 'operator', class: 'operator' },
  ],
  [
    { text: '1', type: 'number', class: 'number' },
    { text: '2', type: 'number', class: 'number' },
    { text: '3', type: 'number', class: 'number' },
    { text: '+', type: 'operator', class: 'operator' },
  ],
  [
    { text: '+/-', type: 'sign', class: 'function' },
    { text: '0', type: 'number', class: 'number' },
    { text: '.', type: 'decimal', class: 'function' },
    { text: '=', type: 'equals', class: 'equals' },
  ],
]

// 删除一位数字
export function deleteLastChar() {
  if (hasCalculated.value) {
    // 如果是计算结果，清除所有
    clear()
    return
  }

  // 如果在括号模式下
  if (expressionParts.value.length > 0) {
    // 如果display有内容且不是'0'，先删除display的内容
    if (display.value !== '0' && display.value.length > 1) {
      display.value = display.value.slice(0, -1)
      currentInput.value = display.value
      updateFormulaDisplay()
      return
    }

    // display为'0'或只有一位，删除表达式的最后部分
    if (expressionParts.value.length > 0) {
      const lastPart = expressionParts.value[expressionParts.value.length - 1]

      // 如果最后部分以右括号结尾，减少openBrackets
      if (lastPart.endsWith(')')) {
        openBrackets.value++
      }
      // 如果最后部分以左括号结尾，减少openBrackets
      else if (lastPart.endsWith('(')) {
        openBrackets.value--
      }

      // 删除最后一个表达式部分
      expressionParts.value.pop()

      // 如果删完了所有表达式部分，退出括号模式
      if (expressionParts.value.length === 0) {
        openBrackets.value = 0
        display.value = '0'
        formula.value = ''
        result.value = ''
      }
      else {
        // 更新显示
        display.value = '0'
      }

      currentInput.value = display.value
      updateFormulaDisplay()
      return
    }
  }

  // 普通模式的删除逻辑
  // 如果有操作符在等待状态，删除操作符
  if (waitingForNewInput.value && operator.value && previousInput.value) {
    operator.value = ''
    waitingForNewInput.value = false
    display.value = previousInput.value
    currentInput.value = display.value
    updateFormulaDisplay()
    return
  }

  if (display.value === '0' || display.value === '') {
    return
  }

  if (display.value.length === 1) {
    display.value = '0'
    if (expressionParts.value.length === 0) {
      // 普通模式下清空公式和结果
      formula.value = ''
      result.value = ''
    }
  }
  else {
    display.value = display.value.slice(0, -1)
  }

  currentInput.value = display.value
  // 更新公式显示
  updateFormulaDisplay()
}

// 更新公式显示
function updateFormulaDisplay() {
  // 如果已经计算完成，不要覆盖显示的结果
  if (hasCalculated.value) {
    return
  }

  // 如果有表达式部分（括号模式）
  if (expressionParts.value.length > 0) {
    // 检查最后一个部分是否以右括号结束
    const lastPart = expressionParts.value[expressionParts.value.length - 1]
    const endsWithCloseBracket = lastPart && lastPart.endsWith(')')
    const endsWithOpenBracket = lastPart && lastPart.endsWith('(')
    const endsWithOperator = lastPart && /[+\-×÷]\s$/.test(lastPart)

    // 判断是否应该添加display值：
    // 1. 不以右括号结束
    // 2. 不是刚输入左括号且显示为'0'
    // 3. 如果以操作符结尾，但display不为'0'，说明用户输入了新数字，应该显示
    const shouldAddDisplay = !endsWithCloseBracket
      && !(endsWithOpenBracket && display.value === '0')
      && !(endsWithOperator && display.value === '0')

    const currentFormula = shouldAddDisplay
      ? expressionParts.value.join('') + display.value
      : expressionParts.value.join('')

    formula.value = currentFormula

    // 尝试计算预览结果
    if (openBrackets.value === 0) {
      try {
        const calculationResult = evaluateSimpleExpression(currentFormula)
        if (calculationResult !== null) {
          result.value = formatResult(calculationResult)
        }
      }
      catch {
        result.value = ''
      }
    }
    return
  }

  // 普通模式的公式显示
  if (previousInput.value && operator.value) {
    if (waitingForNewInput.value) {
      if (fullFormula.value) {
        formula.value = `${fullFormula.value} ${operator.value} `
      }
      else {
        formula.value = `${formatNumber(Number.parseFloat(previousInput.value))} ${operator.value} `
      }
      result.value = ''
    }
    else {
      if (fullFormula.value) {
        formula.value = `${fullFormula.value} ${operator.value} ${display.value}`
      }
      else {
        formula.value = `${formatNumber(Number.parseFloat(previousInput.value))} ${operator.value} ${display.value}`
      }
      calculateRealTime()
    }
  }
  else if (!hasCalculated.value) {
    // 只有在没有计算完成时才设置为display.value
    formula.value = display.value
    result.value = ''
    fullFormula.value = ''
  }
}

// 数字输入处理
export function inputNumber(num: string) {
  if (waitingForNewInput.value || display.value === '0' || hasCalculated.value) {
    display.value = num
    waitingForNewInput.value = false
    hasCalculated.value = false
  }
  else if (display.value.length < MAX_DISPLAY_LENGTH) {
    display.value += num
  }
  currentInput.value = display.value

  // 更新公式显示
  updateFormulaDisplay()
}

// 小数点输入处理
export function inputDecimal() {
  if (waitingForNewInput.value || hasCalculated.value) {
    display.value = '0.'
    waitingForNewInput.value = false
    hasCalculated.value = false
  }
  else if (!display.value.includes('.')) {
    display.value += '.'
  }
  currentInput.value = display.value

  // 更新公式显示
  updateFormulaDisplay()
}

// 操作符输入处理
export function inputOperator(op: string) {
  // 如果刚刚计算完成或选择了历史记录，使用当前结果继续计算
  if (hasCalculated.value) {
    // 使用当前显示的结果作为新计算的起始值
    const currentResult = result.value || display.value
    clear()
    display.value = currentResult
    previousInput.value = currentResult
    operator.value = op
    waitingForNewInput.value = true
    hasCalculated.value = false
    updateFormulaDisplay()
    return
  }

  // 如果在括号模式下
  if (expressionParts.value.length > 0) {
    expressionParts.value.push(`${display.value} ${op} `)
    display.value = '0' // 重置显示内容，准备接受新数字
    waitingForNewInput.value = true
    updateFormulaDisplay()
    return
  }

  // 普通模式的操作符处理
  if (previousInput.value && operator.value && !waitingForNewInput.value) {
    const prev = Number.parseFloat(previousInput.value)
    const current = Number.parseFloat(display.value)
    let calculationResult = 0

    try {
      switch (operator.value) {
        case '+':
          calculationResult = prev + current
          break
        case '-':
          calculationResult = prev - current
          break
        case '×':
          calculationResult = prev * current
          break
        case '÷':
          if (current === 0) {
            display.value = '错误'
            formula.value = '错误'
            result.value = ''
            fullFormula.value = ''
            clear()
            return
          }
          calculationResult = prev / current
          break
        case '%':
          calculationResult = (prev * current) / 100
          break
      }

      if (fullFormula.value) {
        fullFormula.value = `${fullFormula.value} ${operator.value} ${display.value}`
      }
      else {
        fullFormula.value = `${formatNumber(prev)} ${operator.value} ${formatNumber(current)}`
      }

      display.value = formatResult(calculationResult)
    }
    catch {
      display.value = '错误'
      formula.value = '错误'
      result.value = ''
      fullFormula.value = ''
      clear()
      return
    }
  }
  else if (!previousInput.value) {
    fullFormula.value = ''
  }

  previousInput.value = display.value
  operator.value = op
  waitingForNewInput.value = true
  hasCalculated.value = false

  updateFormulaDisplay()
}

// 实时计算结果（不添加历史记录）
function calculateRealTime() {
  if (!previousInput.value || !operator.value || !display.value) {
    return
  }

  const prev = Number.parseFloat(previousInput.value)
  const current = Number.parseFloat(display.value)
  let calculationResult = 0

  try {
    switch (operator.value) {
      case '+':
        calculationResult = prev + current
        break
      case '-':
        calculationResult = prev - current
        break
      case '×':
        calculationResult = prev * current
        break
      case '÷':
        if (current === 0) {
          result.value = '错误'
          return
        }
        calculationResult = prev / current
        break
      case '%':
        calculationResult = (prev * current) / 100
        break
      default:
        return
    }

    // 格式化并显示结果
    result.value = formatResult(calculationResult)
  }
  catch {
    result.value = '错误'
  }
}

// 计算处理（按等号时）
export function calculate() {
  // 如果在括号模式
  if (expressionParts.value.length > 0) {
    // 构建完整表达式
    // 检查最后一个部分是否已经包含了当前的display值
    const lastPart = expressionParts.value[expressionParts.value.length - 1]
    const endsWithCloseBracket = lastPart && lastPart.endsWith(')')

    let fullExpression
    if (endsWithCloseBracket) {
      // 如果最后部分以右括号结尾，说明display.value已经包含在其中了
      fullExpression = expressionParts.value.join('')
    }
    else {
      // 否则需要添加当前的display.value
      fullExpression = expressionParts.value.join('') + display.value
    }

    // 补齐未闭合的括号
    while (openBrackets.value > 0) {
      fullExpression += ')'
      openBrackets.value--
    }

    const calculationResult = evaluateSimpleExpression(fullExpression)
    
    if (calculationResult !== null) {
      const formattedResult = formatResult(calculationResult)

      addToHistory(fullExpression, formattedResult)

      // 立即设置hasCalculated标志，防止其他函数覆盖显示
      hasCalculated.value = true

      // 重置括号状态
      expressionParts.value = []
      openBrackets.value = 0
      currentInput.value = formattedResult
      waitingForNewInput.value = true
      display.value = formattedResult

      // 直接设置结果显示在公式区
      formula.value = formattedResult
      result.value = ''
    }
    else {
      display.value = '错误'
      formula.value = '错误'
      result.value = ''
      clear()
    }
    return
  }

  // 普通模式的计算
  if (!previousInput.value || !operator.value || !currentInput.value) {
    return
  }

  const prev = Number.parseFloat(previousInput.value)
  const current = Number.parseFloat(currentInput.value)
  let calculationResult = 0
  let calculationExpression = ''

  try {
    switch (operator.value) {
      case '+':
        calculationResult = prev + current
        break
      case '-':
        calculationResult = prev - current
        break
      case '×':
        calculationResult = prev * current
        break
      case '÷':
        if (current === 0) {
          display.value = '错误'
          formula.value = '错误'
          result.value = ''
          fullFormula.value = ''
          clear()
          return
        }
        calculationResult = prev / current
        break
      case '%':
        calculationResult = (prev * current) / 100
        break
      default:
        return
    }

    const formattedResult = formatResult(calculationResult)

    if (fullFormula.value) {
      calculationExpression = `${fullFormula.value} ${operator.value} ${formatNumber(current)}`
    }
    else {
      calculationExpression = `${formatNumber(prev)} ${operator.value} ${formatNumber(current)}`
    }

    addToHistory(calculationExpression, formattedResult)

    // 立即设置hasCalculated标志，防止其他函数覆盖显示
    hasCalculated.value = true

    // 清空所有计算状态
    previousInput.value = ''
    operator.value = ''
    currentInput.value = formattedResult
    waitingForNewInput.value = true
    fullFormula.value = ''
    display.value = formattedResult

    // 直接设置结果显示在公式区
    formula.value = formattedResult
    result.value = ''
  }
  catch {
    display.value = '错误'
    formula.value = '错误'
    result.value = ''
    fullFormula.value = ''
    clear()
  }
}

// 清除处理
export function clear() {
  display.value = '0'
  formula.value = ''
  result.value = ''
  currentInput.value = ''
  operator.value = ''
  previousInput.value = ''
  waitingForNewInput.value = false
  hasCalculated.value = false
  fullFormula.value = ''
  expressionParts.value = []
  openBrackets.value = 0
}

// 正负号切换
export function toggleSign() {
  if (display.value !== '0') {
    if (display.value.startsWith('-')) {
      display.value = display.value.substring(1)
    }
    else {
      display.value = `-${display.value}`
    }
    currentInput.value = display.value

    // 更新公式显示
    updateFormulaDisplay()
  }
}

// 百分号处理
export function inputPercent() {
  const num = Number.parseFloat(display.value)
  const calculationResult = num / 100
  const formattedResult = formatResult(calculationResult)
  display.value = formattedResult
  formula.value = `${num}%`
  result.value = formattedResult
  currentInput.value = formattedResult
  hasCalculated.value = true
}

// 括号处理
export function inputParentheses() {
  // 如果当前在等待新输入且有操作符（1 +"），直接在当前公式后添加括号
  if (waitingForNewInput.value && operator.value && !hasCalculated.value) {
    // 进入括号模式，但继承当前的普通计算状态
    expressionParts.value.push(`${formula.value}(`)
    openBrackets.value++
    display.value = '0'
    result.value = ''

    // 清除普通模式状态，完全进入括号模式
    previousInput.value = ''
    operator.value = ''
    fullFormula.value = ''

    updateFormulaDisplay()
    return
  }

  if (display.value === '0' || waitingForNewInput.value || hasCalculated.value) {
    // 输入左括号
    if (expressionParts.value.length === 0 && (formula.value === '' || formula.value === '0')) {
      // 全新开始
      expressionParts.value.push('(')
    }
    else {
      // 检查是否已经在括号模式中
      if (expressionParts.value.length > 0) {
        // 已经在括号模式中，直接添加左括号，不添加乘号
        expressionParts.value.push('(')
      }
      else {
        // 在已有数字后添加乘号和左括号
        expressionParts.value.push(' × (')
      }
    }

    openBrackets.value++
    display.value = '0'
    waitingForNewInput.value = true
    hasCalculated.value = false
    result.value = ''
  }
  else if (openBrackets.value > 0) {
    // 输入右括号
    expressionParts.value.push(`${display.value})`)
    openBrackets.value--

    // 如果所有括号都闭合了，计算预览结果
    if (openBrackets.value === 0) {
      const fullExpression = expressionParts.value.join('')
      try {
        const calculationResult = evaluateSimpleExpression(fullExpression)
        if (calculationResult !== null) {
          result.value = formatResult(calculationResult)
        }
      }
      catch {
        result.value = ''
      }
    }

    // 右括号后，设置为等待新输入状态，但不重置display（避免重复显示）
    waitingForNewInput.value = true
  }

  updateFormulaDisplay()
}

// 简化的表达式求解
function evaluateSimpleExpression(expr: string): number | null {
  try {
    let cleanExpr = expr.trim()

    cleanExpr = cleanExpr.replace(/×/g, '*')
    cleanExpr = cleanExpr.replace(/÷/g, '/')

    if (!/^[\d+\-*/().\s]+$/.test(cleanExpr)) {
      return null
    }

    // eslint-disable-next-line no-new-func
    const func = new Function(`return ${cleanExpr}`)
    const calculationResult = func()

    if (typeof calculationResult === 'number' && Number.isFinite(calculationResult)) {
      return calculationResult
    }

    return null
  }
  catch {
    return null
  }
}

// 按钮点击处理
export function handleButtonClick(button: any) {
  switch (button.type) {
    case 'number':
      inputNumber(button.text)
      break
    case 'decimal':
      inputDecimal()
      break
    case 'operator':
      if (button.text === '%') {
        inputPercent()
      }
      else {
        inputOperator(button.text)
      }
      break
    case 'equals':
      calculate()
      break
    case 'clear':
      clear()
      break
    case 'sign':
      toggleSign()
      break
    case 'parentheses':
      inputParentheses()
      break
  }
}

// 格式化数字显示
function formatNumber(num: number): string {
  if (num === Math.floor(num)) {
    return num.toString()
  }
  return num.toString()
}

// 格式化计算结果
function formatResult(calculationResult: number): string {
  if (Number.isNaN(calculationResult) || !Number.isFinite(calculationResult)) {
    return '错误'
  }

  // 保留合适的小数位数
  let formatted = calculationResult.toString()

  if (formatted.length > MAX_DISPLAY_LENGTH) {
    if (Math.abs(calculationResult) >= 1e12 || Math.abs(calculationResult) < 1e-6) {
      // 使用科学计数法
      formatted = calculationResult.toExponential(6)
    }
    else {
      // 截断小数位数
      const decimalPlaces = MAX_DISPLAY_LENGTH - Math.floor(Math.abs(calculationResult)).toString().length - 1
      formatted = calculationResult.toFixed(Math.max(0, decimalPlaces))
    }
  }

  return formatted
}

// 添加历史记录
function addToHistory(expression: string, calculationResult: string) {
  const calculatorStore = useCalculatorStore()
  const item = {
    id: Date.now().toString(),
    expression,
    result: calculationResult,
    timestamp: new Date().toLocaleString(),
  }
  calculatorStore.addHistory(item)
  history.value = calculatorStore.history
}

// 加载历史记录
export function loadHistoryFromStorage() {
  const calculatorStore = useCalculatorStore()
  history.value = calculatorStore.history
}

// 清空历史记录
export function clearHistory() {
  const calculatorStore = useCalculatorStore()
  calculatorStore.clearHistory()
  history.value = []
}

// 删除历史记录项
export function deleteHistoryItem(id: string) {
  const calculatorStore = useCalculatorStore()
  calculatorStore.deleteHistoryItem(id)
  history.value = calculatorStore.history
}

// 使用历史记录项
export function useHistoryItem(item: any) {
  const calculatorStore = useCalculatorStore()
  const { expression, result } = calculatorStore.useHistoryItem(item)
  display.value = result
  formula.value = expression
  hasCalculated.value = true
  waitingForNewInput.value = true
}

// 切换历史记录显示状态（在显示区域内）
export function toggleHistoryInDisplay() {
  showHistoryInDisplay.value = !showHistoryInDisplay.value
}

// 切换历史记录显示状态（弹窗）
export function toggleHistory() {
  showHistory.value = !showHistory.value
}

// 计算显示的表达式
export const currentExpression = computed(() => {
  if (!previousInput.value || !operator.value) {
    return ''
  }

  let expr = `${formatNumber(Number.parseFloat(previousInput.value))} ${operator.value}`
  if (!waitingForNewInput.value && currentInput.value) {
    expr += ` ${formatNumber(Number.parseFloat(currentInput.value))}`
  }
  return expr
})
